<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/11/10
 * Time: 16:41
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\lib\upload;

use think\Exception;
use think\facade\Filesystem;
use think\Request;

class Base
{
    protected int $maxSize = 2;  //文件大小限制
    protected array $file_type = [
        "image/jpeg",
        "image/png",
        "image/jpe",
        "image/gif"
    ];

    /**
     * @param Request $request
     * @return bool|string
     * @throws Exception
     */
    public function upload(Request $request)
    {
        $file = $request->file();
        $key = array_keys($file);
        //判断大小 //判断类型 //判断格式
        $filename = $request->file($key[0]);
        $this->valSize($filename->getSize());
        $this->valType($filename->getMime());
        return Filesystem::disk('public')->putFile("upload/".$key[0],$filename);
    }

    /**
     * 判断大小
     * @param int $size
     * @throws Exception
     */
    protected function valSize(int $size = 0)
    {
        $maxSize = $this->maxSize * 1024 * 1024;
        if ($size > $maxSize) {
            throw new Exception("文件大小不能超过{$this->maxSize}M");
        }
    }

    /**
     * 判断文件类型
     * @param string $type
     * @throws Exception
     */
    protected function valType(string $type = '')
    {
        if (!in_array($type, $this->file_type)) {
            throw new Exception("文件类型不正确");
        }
    }
}